package com.tourism.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tourism.dao.AttractionCollectDao;
import com.tourism.dao.AttractionDao;
import com.tourism.entity.AttractionCollect;
import com.tourism.entity.AttractionCollectQuery;
import com.tourism.exception.ExceptionEnum;
import com.tourism.exception.GlobalException;
import com.tourism.service.AttractionCollectService;
import com.tourism.util.SystemHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description
 * @Author z
 * @Date 2021-05-01 10:25
 */
@Service
public class AttractionCollectServiceImpl implements AttractionCollectService {

    @Autowired
    private AttractionCollectDao attractionCollectDao;

    @Autowired
    private AttractionDao attractionDao;

    @Override
    public boolean addAttractionCollect(AttractionCollect attractionCollect) throws GlobalException {
        Long userId = SystemHelper.getUserId();
        //验证是否已经收藏过了
        if (isCollected(attractionCollect.getAttractionId())) {
            throw new GlobalException(ExceptionEnum.AttractionCollected);
        }
        attractionCollect.init();
        attractionCollect.setUserId(userId);
        attractionCollectDao.addAttractionCollect(attractionCollect);
        //收藏成功之后，该景点的收藏量+1
        attractionDao.updateCollection(attractionCollect.getAttractionId(), 1);
        return true;
    }
//根据用户ID和景点ID查询是有收藏
    @Override
    public boolean isCollected(Long attractionId) {
        return attractionCollectDao.getDataByUserIdAndAttractionId(SystemHelper.getUserId(), attractionId) != null;
    }

    @Override
    public AttractionCollect getAttractionCollectById(Long id) {
        return attractionCollectDao.getAttractionCollectById(id);
    }

    @Override
    public boolean deleteCollectByAttractionId(Long attractionId) {
        Long attractionCollectId = attractionCollectDao.getDataByUserIdAndAttractionId(SystemHelper.getUserId(), attractionId);
        attractionCollectDao.deleteAttractionCollectById(attractionCollectId);
        //取消收藏成功之后，该景点的收藏量-1
        attractionDao.updateCollection(attractionId, -1);
        return true;
    }

    @Override
    public PageInfo<AttractionCollect> getAttractionCollectList(AttractionCollectQuery query) {
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        //判断是否是管理员（管理员查询所有，否之用户只能查询自己的）
        if (!SystemHelper.isAdmin()) {
            query.setUserId(SystemHelper.getUserId());
        }
        List<AttractionCollect> AttractionList = attractionCollectDao.getAttractionCollectList(query);
        PageInfo<AttractionCollect> result = new PageInfo<>(AttractionList);
        return result;
    }
}
